package com.jt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.ItemDescMapper;
import com.jt.mapper.ItemMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.service.ItemService;
import com.jt.vo.ItemVO;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemDescMapper itemDescMapper;

    @Override
    public PageResult getItemList(PageResult pageResult) {
        IPage page = new Page(pageResult.getPageNum(), pageResult.getPageSize());
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.like(flag, "title", pageResult.getQuery());
        page = itemMapper.selectPage(page, queryWrapper);
        pageResult.setTotal(page.getTotal()).setRows(page.getRecords());
        return pageResult;
    }

    @Override
    public void updateItemStatus(Item item) {
        itemMapper.updateById(item);
    }

    @Override
    @Transactional
    public void deleteItemById(Integer id) {
        itemMapper.deleteById(id);
        itemDescMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void saveItem(ItemVO itemVO) {
        itemMapper.insert(itemVO.getItem().setStatus(true));//Item还未入库，此时Item的ID为null
        //MP实现了主键自动回显
        //ItemDesc入库时绑定Item的ID然后再入库
        itemDescMapper.insert(itemVO.getItemDesc().setId(itemVO.getItem().getId()));
    }

    /**
     * 实现商品新增  Item/ItemDesc  要求ID相同 一一对应.
     * Item主键自增: 只有执行了insert 入库操作之后才会动态分配ID
     * 难点: itemDesc入库时主键为null
     * 解决方案: 实现主键自动回显功能!!!!
     * @param itemVO
     */
//    @Override
//    @Transactional
//    public void saveItem(ItemVO itemVO) {
//        Item item = itemVO.getItem();
//        item.setStatus(true);   //默认启用状态
//        itemMapper.insert(item);//MP自动的实现了主键自动回显
//        ItemDesc itemDesc = itemVO.getItemDesc();
//        itemDesc.setId(item.getId());//MP回显之后取值操作
//        itemDescMapper.insert(itemDesc);
//    }
}
